package com.group.yqxxb.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.group.yqxxb.builder.CheckSumBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.Date;

/**
 * @author hzy
 * 这里是用来生成请求头返回实体响应的类
 * */
public class ApiResponseUtil {

    public HttpPost buildHeader(String url){
        HttpPost httpPost = new HttpPost(url);
        String appKey = "14d25526d8e5c52ffdf46440931d3f48";
        String appSecret = "b2707e7576e7";
        String nonce =  "dxy2013";
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        return httpPost;
    }

    public JSONObject returnJSON(HttpPost httpPost) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        //result2为获得的json字符串
        String result2 = EntityUtils.toString(response.getEntity(), "utf-8");
        JSONObject jsonObject = JSON.parseObject(result2);
        return JSON.parseObject(result2);
    }
}
